using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using System.IO;
using System.Threading.Tasks;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using static ItemData;
using static PlayerStats;
/// <summary>
/// 角色属性结构体
/// </summary>
[Serializable]
public class PlayerStats
{
    public enum AttackType {
        Melee,
        Ranged
    }

    public float interactionRange = 3f;
    public float range = 1.2f;//攻击范围
    public GameObject gameObject;//临时复身变量
    public List<PassiveSkillData> allSkills; // 存储所有技能数据的列表
    public Backpack deserializedBackpack;//背包数据
    // 新增数组：长度等于 Part 枚举成员数，每个索引对应一个身体部位
    public Item[] equippedItems = new Item[Enum.GetValues(typeof(Part)).Length];
    public string avatarImagePath;
    public ImageSliceInfo avatarSliceInfo;
    public string worldImagePath;
    public ImageSliceInfo worldSliceInfo;
    public string name; //角色名字
    public string gender;        // 性别
    public string birthDate;     // 出生日期
    public string location;      // 地点
    public string team;          // 团队
    public string faction;       // 势力
    public string biography;     // 简历
    public string storyBackground; // 故事背景
    public float Hp; // 血量
    public float corrHp; // 血量修正
    public float hpMax; // 血量上限
    public float Speed;//速度
    public float dodge;//闪避
    public float attackPower;//攻击伤害
    public AttackType type = AttackType.Melee;
    public float spirit; //精神
    public float corrSpirit; //精神修正
    public float spiritMax; //精神上限
    public float action; //行动力
    public float corrAction; //行动力修正
    public float actionMax; //行动力上限


    public float physical; // 体力
    public float corrPhysical; // 体力值修正
    public float physicalMax; // 体力值上限

    [Header("耐心")] public float patience; // 耐心
    public float corrPatience; // 耐心修正
    public float patienceMax; // 耐心上限

    public float fishingLevel; // 钓鱼等级
    public float corrfishingLevel; // 钓鱼等级修正
    public float fishingLevelMax; // 钓鱼等级上限
    public float criticalStrikeRate; //暴击率
    public float corrCriticalStrikeRate; //暴击修正
    public float criticalStrikeRateMax; //暴击上限
    public float criticalDamage; //暴击伤害
    public float corrCriticalDamage; //暴击伤害修正
    public float vision = 10; //视野
    public float corrActionVision; //视野修正

    #region 基础 6 大属性

    public float constitution; // 体质
    public float corrConstitution; // 体质修正
    public float constitutionMax; // 体质上限

    public float strength; // 力量
    public float corrStrength; // 力量修正
    public float strengthMax; // 力量上限

    public float agility; // 敏捷
    public float corrAgility; // 敏捷修正
    public float agilityMax; // 敏捷上限

    public float intelligence; // 智力
    public float corrIntelligence; // 智力修正
    public float intelligenceMax; // 智力上限

    public float perception; // 感知
    public float corrPerception; // 感知修正
    public float perceptionMax; // 感知上限

    public float charisma; // 魅力
    public float corrCharisma; // 魅力修正
    public float charismaMax; // 魅力上限

    public float willpower; // 意志
    public float corrWillpower; // 意志修正
    public float willpowerMax; // 意志上限

    public float luck; // 幸运
    public float corrLuck; // 幸运修正
    public float luckMax; // 幸运上限

    public float endurance; // 耐力
    public float corrEndurance; // 耐力修正
    public float enduranceMax; // 耐力上限

    #endregion


    public float GetPropertyValue(string propertyName)
    {
        switch (propertyName)
        {
            case "Hp":
                return Hp;
            case "corrHp":
                return corrHp;
            case "hpMax":
                return hpMax;
            case "spirit":
                return spirit;
            case "corrSpirit":
                return corrSpirit;
            case "spiritMax":
                return spiritMax;
            case "action":
                return action;
            case "corrAction":
                return corrAction;
            case "actionMax":
                return actionMax;
            case "physical":
                return physical;
            case "corrPhysical":
                return corrPhysical;
            case "physicalMax":
                return physicalMax;
            case "patience":
                return patience;
            case "corrPatience":
                return corrPatience;
            case "patienceMax":
                return patienceMax;
            case "fishingLevel":
                return fishingLevel;
            case "corrfishingLevel":
                return corrfishingLevel;
            case "fishingLevelMax":
                return fishingLevelMax;
            case "criticalStrikeRate":
                return criticalStrikeRate;
            case "corrCriticalStrikeRate":
                return corrCriticalStrikeRate;
            case "criticalStrikeRateMax":
                return criticalStrikeRateMax;
            case "criticalDamage":
                return criticalDamage;
            case "corrCriticalDamage":
                return corrCriticalDamage;
            case "vision":
                return vision;
            case "corrActionVision":
                return corrActionVision;
            case "constitution":
                return constitution;
            case "corrConstitution":
                return corrConstitution;
            case "constitutionMax":
                return constitutionMax;
            case "strength":
                return strength;
            case "corrStrength":
                return corrStrength;
            case "strengthMax":
                return strengthMax;
            case "agility":
                return agility;
            case "corrAgility":
                return corrAgility;
            case "agilityMax":
                return agilityMax;
            case "intelligence":
                return intelligence;
            case "corrIntelligence":
                return corrIntelligence;
            case "intelligenceMax":
                return intelligenceMax;
            case "perception":
                return perception;
            case "corrPerception":
                return corrPerception;
            case "perceptionMax":
                return perceptionMax;
            case "charisma":
                return charisma;
            case "corrCharisma":
                return corrCharisma;
            case "charismaMax":
                return charismaMax;
            case "willpower":
                return willpower;
            case "corrWillpower":
                return corrWillpower;
            case "willpowerMax":
                return willpowerMax;
            case "luck":
                return luck;
            case "corrLuck":
                return corrLuck;
            case "luckMax":
                return luckMax;
            case "endurance":
                return endurance;
            case "corrEndurance":
                return corrEndurance;
            case "enduranceMax":
                return enduranceMax;
            default:
                Debug.LogWarning($"找不到名为 {propertyName} 的属性");
                return 0;
        }
    }
}

// 更新类
public static class PlayerStatsExtensions
{
    public static PlayerStats UpdateInfo(this PlayerStats playerStats) //更新基础信息
    {
        //血量计算
        playerStats.hpMax = (playerStats.constitution + playerStats.corrConstitution) * 3;

        //精神计算
        playerStats.spiritMax = (playerStats.intelligence + playerStats.corrIntelligence + playerStats.willpower +
                                 playerStats.corrWillpower) * 1.5f;
        //行动力
        playerStats.actionMax = (playerStats.agility + playerStats.corrAgility) / 10;
        //暴击率
        playerStats.criticalStrikeRate = (0.5f + playerStats.luck + playerStats.corrLuck) / 10f;
        //视野
        playerStats.vision = (playerStats.perception + playerStats.corrPerception) / 10;
        //体力值计算公式
        playerStats.physicalMax = 120 + playerStats.constitution + playerStats.constitution;
        return playerStats;
    }

    public static PlayerStats DataInfo(this PlayerStats playerStats) //数据初始化
    {
        playerStats.Hp = playerStats.hpMax;
        playerStats.spirit = playerStats.spiritMax;
        playerStats.action = playerStats.actionMax;
        playerStats.agility = playerStats.agilityMax;
        playerStats.criticalStrikeRate = playerStats.criticalStrikeRateMax;
        playerStats.physical = playerStats.physicalMax;
        return playerStats;
    }

    public static string GetValueNames(this PlayerStats playerStats, string operation,
        (string prefix, object data)[] objects) //获取变量对照名字
    {
        // 创建中英文映射字典
        Dictionary<string, string> nameMapping = new Dictionary<string, string>
        {
            { "Hp", "血量" },
            { "corrHp", "血量修正" },
            { "hpMax", "血量上限" },
            { "spirit", "精神" },
            { "corrSpirit", "精神修正" },
            { "spiritMax", "精神上限" },
            { "action", "行动力" },
            { "corrAction", "行动力修正" },
            { "actionMax", "行动力上限" },
            { "physical", "体力" },
            { "corrPhysical", "体力值修正" },
            { "physicalMax", "体力值上限" },
            { "patience", "耐心" },
            { "corrPatience", "耐心修正" },
            { "patienceMax", "耐心上限" },
            { "fishingLevel", "钓鱼等级" },
            { "corrfishingLevel", "钓鱼等级修正" },
            { "fishingLevelMax", "钓鱼等级上限" },
            { "criticalStrikeRate", "暴击率" },
            { "corrCriticalStrikeRate", "暴击修正" },
            { "criticalStrikeRateMax", "暴击上限" },
            { "criticalDamage", "暴击伤害" },
            { "corrCriticalDamage", "暴击伤害修正" },
            { "vision", "视野" },
            { "corrActionVision", "视野修正" },
            { "constitution", "体质" },
            { "corrConstitution", "体质修正" },
            { "constitutionMax", "体质上限" },
            { "strength", "力量" },
            { "corrStrength", "力量修正" },
            { "strengthMax", "力量上限" },
            { "agility", "敏捷" },
            { "corrAgility", "敏捷修正" },
            { "agilityMax", "敏捷上限" },
            { "intelligence", "智力" },
            { "corrIntelligence", "智力修正" },
            { "intelligenceMax", "智力上限" },
            { "perception", "感知" },
            { "corrPerception", "感知修正" },
            { "perceptionMax", "感知上限" },
            { "charisma", "魅力" },
            { "corrCharisma", "魅力修正" },
            { "charismaMax", "魅力上限" },
            { "willpower", "意志" },
            { "corrWillpower", "意志修正" },
            { "willpowerMax", "意志上限" },
            { "luck", "幸运" },
            { "corrLuck", "幸运修正" },
            { "luckMax", "幸运上限" },
            { "endurance", "耐力" },
            { "corrEndurance", "耐力修正" },
            { "enduranceMax", "耐力上限" },
            { "Richness", "丰富度" },
            { "RichnessMax", "丰富度上限" },
            { "difficultyInCollection", "采集难度" },
            { "corrDifficultyInCollection", "采集难度修正" },
            { "basicSuccessRate", "成功率" },
            { "currentEvent", "当前事件成功率" },
            { "corrBasicSuccessRate", "基础成功率修正" },
            { "basicSuccessRateMax", "基础成功率最大值" },
        };

        // 解析操作字符串，替换属性名
        string[] operations = operation.Split(';');
        string result = "";
        foreach (string op in operations)
        {
            string[] parts = op.Split(new string[] { "+=", "-=", "*=", "/=" }, StringSplitOptions.None);
            if (parts.Length == 2)
            {
                string varName = parts[0].Trim();
                string valueStr = parts[1].Trim();

                // 提取操作符
                string opSymbol = "";
                if (op.Contains("+="))
                {
                    opSymbol = "+";
                }
                else if (op.Contains("-="))
                {
                    opSymbol = "-";
                }
                else if (op.Contains("*="))
                {
                    opSymbol = "*";
                }
                else if (op.Contains("/="))
                {
                    opSymbol = "/";
                }


                string[] varParts = varName.Split('_');
                if (varParts.Length == 2)
                {
                    string prefix = varParts[0];
                    string fieldName = varParts[1];

                    string objectName = "";
                    foreach (var (p, _) in objects)
                    {
                        if (p == prefix)
                        {
                            objectName = p;
                            break;
                        }
                    }

                    if (nameMapping.TryGetValue(fieldName, out string chineseFieldName))
                    {
                        result += $"{objectName}{chineseFieldName} {opSymbol} {valueStr}\n";
                    }
                }
            }
        }

        return result;
    }

    public static PlayerStats jsonToPlayerStats(string json)//json 转角色数据
    {
        PlayerStats playerStats = JsonUtility.FromJson<PlayerStats>(json);
        return playerStats;
    }

    public static PlayerStats LoadPlayerJson(string jsonFileName)//从 json文件内加载数据
    {
        string path = Path.Combine("Assets/PlayerData", jsonFileName);
        if (File.Exists(path))
        {
            string json = File.ReadAllText(path);
            PlayerStats playerStats = jsonToPlayerStats(json);
            return playerStats;
        }
        else
        {
            Debug.LogError("找不到指定的 JSON 文件: " + path);
            return null;
        }
    }
    public static async Task<PlayerStats> LoadPlayerJsonAsync(string addressKey)
    {
        var handle = Addressables.LoadAssetAsync<TextAsset>("Assets/PlayerData/"+addressKey);
        await handle.Task;  // 等待加载完成（不会堵主线程）

            try
            {
                if (handle.Status == AsyncOperationStatus.Succeeded)
                {
                    string json = handle.Result.text;
                    return  jsonToPlayerStats(json);
                }
                else
                {
                    throw handle.OperationException ?? new Exception("未知加载错误");
                }
            }finally
            {
                Addressables.Release(handle);
            }
    }
    /// <summary>
    /// 回调版：调用上面的 async 方法，并把结果传给 onLoaded
    /// </summary>
    public static void LoadPlayerJson(string addressKey, Action<PlayerStats> onLoaded)
    {
        // 这里用 async void 包一层，保证在主线程里执行 callback
        async void Runner()
        {
            try
            {
                var stats = await LoadPlayerJsonAsync(addressKey);
                onLoaded?.Invoke(stats);
            }
            catch (Exception ex)
            {
                Debug.LogError($"加载 JSON 出错：{ex}");
                onLoaded?.Invoke(null);
            }
        }

        Runner();
    }
    public static void LoadData(this PlayerStats playerStats, string RoleId) //给对象加载数据
    {

        playerStats = LoadPlayerJson(RoleId);

        playerStats.UpdateInfo();
        playerStats.DataInfo();
    }
}
